import { Body, Inject, Provide } from '@midwayjs/decorator';
import { BaseService, CoolCommException } from '@cool-midway/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Any, Repository } from 'typeorm';
import { DoupiaopiaoOrderEntity } from '../entity/order';
import { DoupiaopiaoUserEntity } from '../entity/user';
import { MangoOrderService } from '../../mango/service/order';
import { Context } from '@midwayjs/koa';
import { DoupiaopiaoVoteEntity } from '../entity/vote';
import { DoupiaopiaoDouyinService } from './douyin';
import { DoupiaopiaoCommissionEntity } from '../entity/commission';
import { DoupiaopiaoInvitationEntity } from '../entity/invitation';
import { DoupiaopiaoSettingEntity } from '../entity/setting';
import { DoupiaopiaoTblistEntity } from '../entity/tborder';
import { DoupiaopiaoCarmiEntity } from '../entity/carmi';
import { DoupiaopiaoCardlistEntity } from '../entity/cardlist';
import { DoupiaopiaoCertificatelistEntity } from '../entity/certificatelist';
const qrcode = require('qrcode');
const fs = require('fs');

/**
 * 订单相关
 */
@Provide()
export class DoupiaopiaoOrderService extends BaseService {
  @InjectEntityModel(DoupiaopiaoOrderEntity)
  doupiaopiaoOrderEntity: Repository<DoupiaopiaoOrderEntity>;
  @InjectEntityModel(DoupiaopiaoTblistEntity)
  doupiaopiaoTblistEntity: Repository<DoupiaopiaoTblistEntity>;
  @InjectEntityModel(DoupiaopiaoCommissionEntity)
  doupiaopiaoCommissionEntity: Repository<DoupiaopiaoCommissionEntity>;
  @InjectEntityModel(DoupiaopiaoVoteEntity)
  doupiaopiaoVoteEntity: Repository<DoupiaopiaoVoteEntity>;
  @InjectEntityModel(DoupiaopiaoUserEntity)
  doupiaopiaoUserEntity: Repository<DoupiaopiaoUserEntity>;
  @InjectEntityModel(DoupiaopiaoInvitationEntity)
  doupiaopiaoInvitationEntity: Repository<DoupiaopiaoInvitationEntity>;
  @InjectEntityModel(DoupiaopiaoSettingEntity)
  doupiaopiaoSettingEntity: Repository<DoupiaopiaoSettingEntity>;
  @InjectEntityModel(DoupiaopiaoCarmiEntity)
  doupiaopiaoCarmiEntity: Repository<DoupiaopiaoCarmiEntity>;
  @InjectEntityModel(DoupiaopiaoCardlistEntity)
  doupiaopiaoCardlistEntity: Repository<DoupiaopiaoCardlistEntity>;
  @InjectEntityModel(DoupiaopiaoCertificatelistEntity)
  doupiaopiaoCertificatelistEntity: Repository<DoupiaopiaoCertificatelistEntity>;
  @Inject()
  mangoOrderService: MangoOrderService;
  @Inject()
  doupiaopiaoDouyinService: DoupiaopiaoDouyinService;
  @Inject()
  ctx: Context;

  async createOrder(orderInfo) {
    const { userId } = this.ctx.app_userinfo;
    // 请求芒果电影票锁座下单接口
    const mangoCreateOrderRes: any = await this.mangoCreateOrder(orderInfo);
    console.log(mangoCreateOrderRes);
    try {
      const data = {
        userId: userId,
        orderNo: mangoCreateOrderRes.order_info.order_number,
        normalPayAmount: mangoCreateOrderRes.final_price,
        quickPayAmount: mangoCreateOrderRes.rule_price,
        originalPrice: mangoCreateOrderRes.maoyan_price,
        ticketNum: mangoCreateOrderRes.ticket_num,
        allowChangeSeat: mangoCreateOrderRes.auto_check_seat,
        userPhone: mangoCreateOrderRes.tel,
        movieId: mangoCreateOrderRes.film_id,
        cinemaLineId: mangoCreateOrderRes.line_id,
        cityId: mangoCreateOrderRes.cinemainfo.city_id,
        cinemaId: mangoCreateOrderRes.cinemaid,
        cinemaCode: mangoCreateOrderRes.cinemainfo.cinema_code,
        scheduleId: mangoCreateOrderRes.room_id,
        startTime: mangoCreateOrderRes.roominfo.show_time,
        duration: Number(mangoCreateOrderRes.roominfo.duration),
        movieName: mangoCreateOrderRes.filminfo.name,
        cityName: mangoCreateOrderRes.city,
        cinemaName: mangoCreateOrderRes.cinemainfo.cinema_name,
        cinemaAddres: mangoCreateOrderRes.cinemainfo.cinema_addr,
        hallName: mangoCreateOrderRes.roominfo.hall_name,
        scheduleDesc: mangoCreateOrderRes.show_version_type,
        moviePoster: mangoCreateOrderRes.filminfo.pic,
        seatData: mangoCreateOrderRes.seatdata,
        isQuick: mangoCreateOrderRes.fast_if,
      };
      const createOrderRes = await this.doupiaopiaoOrderEntity.save(data);

      return createOrderRes;
    } catch (error) {
      throw new CoolCommException('创建订单失败（2）');
    }
  }
  //淘宝创建订单接口
  async createdOrderByTb(orderData) {
    const { userId } = this.ctx.app_userinfo;
    const data = {
      userId: userId,
      normalPayAmount: orderData.normalPayAmount,
      quickPayAmount: orderData.quickPayAmount,
      originalPrice: orderData.originalPrice,
      ticketNum: orderData.ticketNum,
      // allowChangeSeat: orderData.allowChangeSeat,
      userPhone: orderData.userPhone,
      movieId: orderData.movieId,
      // cinemaLineId: orderData.cinemaLineId,
      cityId: orderData.cityId,
      cinemaId: orderData.cinemaId,
      cinemaCode: orderData.cinemaCode,
      scheduleId: orderData.scheduleId,
      startTime: orderData.startTime,
      duration: Number(orderData.duration),
      movieName: orderData.movieName,
      // cityName: orderData.cityName,
      // cinemaName: orderData.cinemaName,
      // cinemaAddres: orderData.cinemaAddres,
      hallName: orderData.hallName,
      scheduleDesc: orderData.scheduleDesc,
      moviePoster: orderData.moviePoster,
      seatData: orderData.seatData,
      filmCode: orderData.extraParams,
      // isQuick: orderData.isQuick,
    };
    // return data;

    try {
      const createOrderRes = await this.doupiaopiaoOrderEntity.save(data);
      console.log(createOrderRes, 'createOrderRescreateOrderRes');

      return createOrderRes;
    } catch (error) {
      console.log(error);
      console.log(data);

      throw new CoolCommException('创建订单失败（2）');
    }
  }
  //判断当前的用户中 是否存在芒果空订单
  // 1 可以创建  0 不可创建
  async checkOrder(option) {
    const { userId } = this.ctx.app_userinfo;

    try {
      const mgRes = await this.doupiaopiaoOrderEntity.find({
        where: { userId },
      });
      if (mgRes.length) {
        // 过滤出dyPayOrderNo字段为空的对象并删除
        const objectsToDelete = mgRes.filter(
          item => !item.dyPayOrderNo || !item.orderNo
        );
        if (objectsToDelete.length) {
          return 0;
        } else {
          return 1;
        }
        // for (const object of objectsToDelete) {
        //   await this.doupiaopiaoOrderEntity.remove(object);
        // }
      }
    } catch (error) {
      throw new CoolCommException('操作失败');
    }
  }
  //删除当前用户的空订单
  async delCheckOrder(option) {
    const { userId } = this.ctx.app_userinfo;
    try {
      const mgRes = await this.doupiaopiaoOrderEntity.find({
        where: { userId },
      });
      if (mgRes.length) {
        // 过滤出dyPayOrderNo字段为空的对象并删除
        const objectsToDelete = mgRes.filter(
          item => !item.dyPayOrderNo || !item.orderNo
        );
        if (objectsToDelete.length) {
          for (const object of objectsToDelete) {
            await this.doupiaopiaoOrderEntity.remove(object);
          }
          return 1;
        } else {
          return 0;
        }
      }
    } catch (error) {
      return new CoolCommException('操作失败');
    }
  }

  // 芒果创建订单接口
  async mangoCreateOrder({ tel, room_id, film_id, film_code, seat_data }) {
    try {
      return await this.mangoOrderService.createOrder({
        tel,
        room_id,
        film_id,
        film_code,
        seat_data,
      });
    } catch (error) {
      throw new CoolCommException('创建订单失败（1）');
    }
  }
  // 查询订单详情
  async getDetail(id: number) {
    const { userId } = this.ctx.app_userinfo;
    const order = await this.doupiaopiaoOrderEntity.findOneBy({ userId, id });
    if (order) {
      return order;
    } else {
      throw new CoolCommException('数据不存在');
    }
  }
  // 查询订单列表
  async getList(query) {
    const { userId } = this.ctx.app_userinfo;
    query.userId = userId;
    const option = {
      fieldEq: ['userId', 'orderProgress'],
    };
    if (query.orderProgress === '') {
      delete query.orderProgress;
    }
    return await super.page(query, option);
  }
  //确认出票回调接口
  async payCallBack(requestBody) {
    console.log(requestBody, 'callBack回调参数');
    const { code, order_number } = requestBody;
    try {
      const resultDetail: any = await this.mangoOrderService.updateDetail({
        order_number,
      }); //获取到订单详情
      const order = await this.doupiaopiaoOrderEntity.findOneBy({
        orderNo: requestBody.order_number,
      });
      // 分拥逻辑 start
      //获取当前邀请的信息
      // const inviteRes = await this.doupiaopiaoInvitationEntity.findOneBy({
      //   userId: order.userId,
      // });
      // const myuser = await this.doupiaopiaoUserEntity.findOneBy({
      //   id: parseInt(order.userId),
      // });
      // const commissionMoney = await this.doupiaopiaoSettingEntity.findOneBy({
      //   model_name: 'commission',
      // });
      // const TwoCommission = await this.doupiaopiaoSettingEntity.findOneBy({
      //   model_name: 'TwoCommission',
      // });
      // let totalMoney = 0;
      // let payState = resultDetail.handle_step === 3 ? 1 : 0;
      // if (order.isQuick) {
      //   totalMoney = order.quickPayAmount * order.ticketNum;
      // } else {
      //   totalMoney = order.normalPayAmount * order.ticketNum;
      // }
      // let commissionAmountA = totalMoney * commissionMoney.val_data;
      // let commissionAmountB = totalMoney * TwoCommission.val_data;
      // const fansLevel1 = await this.doupiaopiaoUserEntity.findOneBy({
      //   id: myuser.shareUserId,
      // });
      // //分佣给1级上级
      // if (fansLevel1) {
      //   fansLevel1.balance += commissionAmountA;
      //   await this.doupiaopiaoUserEntity.save(fansLevel1);
      //   await this.doupiaopiaoCommissionEntity.save({
      //     userId: fansLevel1.id.toString(),
      //     orderId: order.orderNo,
      //     state: resultDetail.pay_state,
      //     payState: payState,
      //     endPrice: commissionAmountA,
      //     totalPrice: totalMoney,
      //     level: inviteRes.shareUserLevel,
      //   });
      // }
      // // 查找二级上级
      // const fansLevel2 = await this.doupiaopiaoUserEntity.findOneBy({
      //   id: fansLevel1.id,
      // });

      // // 分佣给二级上级
      // if (fansLevel2) {
      //   fansLevel2.balance += commissionAmountB;
      //   await this.doupiaopiaoUserEntity.save(fansLevel2);
      //   await this.doupiaopiaoCommissionEntity.save({
      //     userId: fansLevel2.id.toString(),
      //     orderId: order.orderNo,
      //     state: resultDetail.pay_state,
      //     payState: payState,
      //     endPrice: commissionAmountB,
      //     totalPrice: totalMoney,
      //     level: inviteRes.shareUserLevel,
      //   });
      // }

      //分佣逻辑结束 end

      if (resultDetail && order) {
        order.payStatus = resultDetail.pay_state;
        order.orderProgress = resultDetail.handle_step;
        order.extraParams = resultDetail.attach;
        order.refundReason = resultDetail.refundmes;
        if (code == '000') {
          order.seatData = resultDetail.seat_data;
        }
      }

      await this.doupiaopiaoOrderEntity.save(order);
      if (code == '000') {
        await this.doupiaopiaoVoteEntity.delete({ orderId: order_number });
        const mangoDetail: any = await this.mangoOrderService.updateDetail({
          order_number,
        }); //获取到订单详情
        mangoDetail.tickets.forEach(async ele => {
          const row = {
            orderId: mangoDetail.order_number,
            oldImgsWz: ele.old_imgs_wz,
            oldTextYcode: ele.old_text_ycode,
            oldTextInfo: ele.old_text_info,
            textInfo: ele.text_info,
          };

          await this.doupiaopiaoVoteEntity.save(row);
        });
      } else if (code == '056') {
        const obj = await this.doupiaopiaoOrderEntity.findOneBy({
          orderNo: order_number,
        });

        const refundData = {
          out_order_no: order_number,
          out_refund_no: this.generateRefundOrderNumber(),
          notify_url: '',
          order_entry_schema: {
            path: 'pages/zhifu-detail/index',
            params: obj.id,
          },
          item_order_detail: [
            {
              item_order_id: '',
            },
          ],
          refund_total_amount: obj.totalCommission * 100,
        };
        await this.doupiaopiaoDouyinService.RefundOrder(refundData);
      } else if (code == '050') {
      } else if (code == '022') {
      } else if (code == '026') {
      }
      return { code: 1 };
    } catch (error) {
      console.error('更新订单时发生错误:', error);
      return new CoolCommException('服务器错误');
    }
  }
  generateRefundOrderNumber() {
    const timestamp = Date.now().toString();
    const randomStr = Math.random().toString(36).substring(2, 8);
    return timestamp + randomStr;
  }

  //payMoney 确认下单
  async payMoney(query) {
    // const { userId } = this.ctx.app_userinfo;
    // console.log(query, '打印一下获取的订单信息');
    try {
      // await this.mangoOrderService.confirmOrder({
      //   order_number: query.order_number,
      //   auto_check_seat: query.auto_check_seat,
      //   fast_buy: query.fast_buy,
      // });

      const orderRes = await this.doupiaopiaoOrderEntity.findOneBy({
        id: query.order_number,
      });
      const user = await this.doupiaopiaoUserEntity.findOneBy({
        id: parseInt(orderRes.userId),
      });

      if (orderRes) {
        orderRes.allowChangeSeat = query.auto_check_seat;
        orderRes.isQuick = query.fast_buy;
        // orderRes.payStatus = 1;
        // orderRes.orderProgress = 1;
      }
      await this.doupiaopiaoOrderEntity.save(orderRes);
      return this.doupiaopiaoOrderEntity.save(orderRes);
      // [[[[[]]]]]
      // 分拥逻辑 start
      //获取当前邀请的信息
      // }
      // try {
      //   const inviteRes = await this.doupiaopiaoInvitationEntity.findOneBy({
      //     userId: orderRes.userId,
      //   });
      //   const myuser = await this.doupiaopiaoUserEntity.findOneBy({
      //     id: parseInt(orderRes.userId),
      //   });
      //   // if (inviteRes) {
      //   const commissionMoney = await this.doupiaopiaoSettingEntity.findOneBy({
      //     model_name: 'commission',
      //   });
      //   const TwoCommission = await this.doupiaopiaoSettingEntity.findOneBy({
      //     model_name: 'TwoCommission',
      //   });
      //   let totalMoney = 0;
      //   // let payState = resultDetail.handle_step === 3 ? 1 : 0;
      //   let payState = 1;
      //   if (orderRes.isQuick) {
      //     totalMoney = orderRes.quickPayAmount;
      //   } else {
      //     totalMoney = orderRes.normalPayAmount;
      //   }
      //   let commissionAmountA = totalMoney * commissionMoney.val_data;
      //   let commissionAmountB = totalMoney * TwoCommission.val_data;
      //   const fansLevel1 = await this.doupiaopiaoUserEntity.findOneBy({
      //     id: myuser.shareUserId,
      //   });
      //   //分佣给1级上级
      //   if (fansLevel1) {
      //     console.log(fansLevel1, '===========1');

      //     // fansLevel1.balance += commissionAmountA;
      //     fansLevel1.balance =
      //       fansLevel1.balance * 100 + commissionAmountA * 100;

      //     await this.doupiaopiaoUserEntity.save(fansLevel1);
      //     await this.doupiaopiaoCommissionEntity.save({
      //       userId: fansLevel1.id.toString(),
      //       orderId: orderRes.orderNo,
      //       state: 1,
      //       payState: payState,
      //       endPrice: commissionAmountA * 100,
      //       totalPrice: totalMoney,
      //       level: inviteRes.shareUserLevel,
      //     });
      //   }
      //   // 查找二级上级
      //   const fansLevel2 = await this.doupiaopiaoUserEntity.findOneBy({
      //     id: fansLevel1.shareUserId,
      //   });

      //   // 分佣给二级上级
      //   if (fansLevel2) {
      //     console.log(fansLevel2, '===========2');

      //     // fansLevel2.balance += commissionAmountB;
      //     fansLevel2.balance =
      //       fansLevel2.balance * 100 + commissionAmountB * 100;

      //     await this.doupiaopiaoUserEntity.save(fansLevel2);
      //     await this.doupiaopiaoCommissionEntity.save({
      //       userId: fansLevel2.id.toString(),
      //       orderId: orderRes.orderNo,
      //       state: 1,
      //       payState: payState,
      //       endPrice: commissionAmountB * 100,
      //       totalPrice: totalMoney,
      //       level: inviteRes.shareUserLevel,
      //     });
      //   }
      // } catch (error) {
      //   console.log(error);

      //   throw error;
      // }

      //分佣逻辑结束 end

      // []]]]]]]][[[][]]]
      // return;

      // const dyRes = await this.doupiaopiaoDouyinService.ReadyOrder(
      //   orderRes,
      //   user
      // );
      // if (dyRes) {
      //   const myOrder = await this.doupiaopiaoOrderEntity.findOneBy({
      //     orderNo: dyRes.out_order_no,
      //   });
      //   myOrder.dyPayOrderNo = dyRes.order_id;
      //   await this.doupiaopiaoOrderEntity.save(orderRes);
      // }
      // return dyRes;
    } catch (error) {
      throw new CoolCommException('下单失败123');
    }
  }
  //获取票的订单信息
  async getVoteDetail(query) {
    console.log(query);
    try {
      const res = await this.doupiaopiaoVoteEntity.find({
        where: { orderId: query.orderId },
      });
      if (res.length) {
        return res;
      } else {
        return [];
      }
    } catch (error) {
      throw new CoolCommException('暂无词条数据');
    }
  }
  //支付回调地址
  async orderStatusBack(body) {
    try {
      const orderRes = await this.doupiaopiaoOrderEntity.findOneBy({
        dyPayOrderNo: body.msg.order_id,
      });
      if (body.type == 'payment') {
        if (body.msg.status == 'SUCCESS') {
          orderRes.payStatus = 1;
          orderRes.orderProgress = 1;
          await this.mangoOrderService.confirmOrder({
            order_number: orderRes.orderNo,
            auto_check_seat: orderRes.allowChangeSeat,
            fast_buy: orderRes.isQuick,
          });
          await this.doupiaopiaoOrderEntity.save(orderRes);
        }
      }
      if (orderRes) {
      }
    } catch (error) {}
  }
  //退款回调
  async orderRefund(body) {
    try {
      if (body.type == 'refund') {
        if (body.msg.status == 'SUCCESS') {
          const result = await this.doupiaopiaoOrderEntity.findOneBy({
            dyPayOrderNo: body.msg.order_id,
          });
          result.payStatus = -1;
          await this.doupiaopiaoOrderEntity.save(result);
        }
      }
    } catch (error) {}
  }
  //生成二维码
  async Qrcode(query) {
    try {
      const qrCodeDataUrl = await qrcode.toDataURL(query.other);
      const qrCodeImageBase64 = qrCodeDataUrl.split(',')[1];
      return qrCodeImageBase64;
    } catch (error) {
      throw new CoolCommException('生成二维码失败');
    }
  }
  //保存淘宝的订单
  async savedOrder(body) {
    const { userId } = this.ctx.app_userinfo;
    console.log(body);
    const userRes = await this.doupiaopiaoUserEntity.findOneBy({
      id: userId,
    });
    try {
      body.forEach(async item => {
        const data = {
          userId: userId,
          status: item.status,
          tborderId: item.id,
          buyer_open_id: item.buyer_open_uid,
          tbTotalMoney: item.payment,
          tb_skuid: item.orders.order[0].sku_id,
          tb_title: item.orders.order[0].title,
          tb_num: item.orders.order[0].num,
          tb_price: item.orders.order[0].price,
        };
        await this.doupiaopiaoTblistEntity.save(data);
        // if (
        //   item.buyer_open_uid == userRes.tbOpenid &&
        //   item.status == 'WAIT_SELLER_SEND_GOODS'
        // ) {
        // }
      });
      const tbRes = await this.doupiaopiaoTblistEntity.find({
        where: { userId: userId },
      });
      const mgRes = await this.doupiaopiaoTblistEntity.find({
        where: { userId: userId },
      });
      tbRes.forEach(tbUserItem => {});
    } catch (error) {
      throw new CoolCommException('创建订单失败（2）');
    }
  }
  //核销票码
  async verifiCation(query) {
    const { userId } = this.ctx.app_userinfo;
    const { cardNumber } = query;
    const cardRes = await this.doupiaopiaoCarmiEntity.findOneBy({
      cardNumber,
    });
    console.log(cardRes);
    if (!cardNumber) {
      return null;
    }
    if (cardRes) {
      cardRes.state = 1;
      // await this.doupiaopiaoCarmiEntity.save(cardRes);
      await cardRes.save();
    }
    if (cardRes && cardRes.cardType == 1 && !cardRes.state) {
      const data = {
        cardId: cardRes.cardNumber,
        state: 1,
        cardType: cardRes.cardType,
        cardValue: cardRes.cardValue,
        userId: userId,
      };
      return 1;
      await this.doupiaopiaoCardlistEntity.save(data);
    } else if (cardRes && cardRes.cardType == 0 && !cardRes.state) {
      const data = {
        cardId: cardRes.cardNumber,
        state: 1,
        cardType: cardRes.cardType,
        cardValue: cardRes.cardValue,
        userId: userId,
      };
      await this.doupiaopiaoCertificatelistEntity.save(data);
      return 1;
    } else {
    }
  }
  //咸鱼解密数据
  async DecryptData(body) {
    try {
      let type = typeof body.data;
      if (type == 'object') {
        body.data = JSON.stringify(body.data);
        console.log(typeof body.data, '123');
      }
      if (type == 'string' && body.data.indexOf('req') === -1) {
        body.data = JSON.stringify(body.data);
        console.log(typeof body.data, '456');
      }

      return this.h(body.token + '&' + body.i + '&' + body.g + '&' + body.data);
    } catch (error) {
      throw new CoolCommException('加密失败');
    }
  }

  h(a) {
    function b(a, b) {
      return (a << b) | (a >>> (32 - b));
    }
    function c(a, b) {
      var c, d, e, f, g;
      return (
        (e = 2147483648 & a),
        (f = 2147483648 & b),
        (c = 1073741824 & a),
        (d = 1073741824 & b),
        (g = (1073741823 & a) + (1073741823 & b)),
        c & d
          ? 2147483648 ^ g ^ e ^ f
          : c | d
          ? 1073741824 & g
            ? 3221225472 ^ g ^ e ^ f
            : 1073741824 ^ g ^ e ^ f
          : g ^ e ^ f
      );
    }
    function d(a, b, c) {
      return (a & b) | (~a & c);
    }
    function e(a, b, c) {
      return (a & c) | (b & ~c);
    }
    function f(a, b, c) {
      return a ^ b ^ c;
    }
    function g(a, b, c) {
      return b ^ (a | ~c);
    }
    function h(a, e, f, g, h, i, j) {
      return (a = c(a, c(c(d(e, f, g), h), j))), c(b(a, i), e);
    }
    function i(a, d, f, g, h, i, j) {
      return (a = c(a, c(c(e(d, f, g), h), j))), c(b(a, i), d);
    }
    function j(a, d, e, g, h, i, j) {
      return (a = c(a, c(c(f(d, e, g), h), j))), c(b(a, i), d);
    }
    function k(a, d, e, f, h, i, j) {
      return (a = c(a, c(c(g(d, e, f), h), j))), c(b(a, i), d);
    }
    function l(a) {
      for (
        var b,
          c = a.length,
          d = c + 8,
          e = (d - (d % 64)) / 64,
          f = 16 * (e + 1),
          g = new Array(f - 1),
          h = 0,
          i = 0;
        c > i;

      )
        (b = (i - (i % 4)) / 4),
          (h = (i % 4) * 8),
          (g[b] = g[b] | (a.charCodeAt(i) << h)),
          i++;
      return (
        (b = (i - (i % 4)) / 4),
        (h = (i % 4) * 8),
        (g[b] = g[b] | (128 << h)),
        (g[f - 2] = c << 3),
        (g[f - 1] = c >>> 29),
        g
      );
    }
    function m(a) {
      var b,
        c,
        d = '',
        e = '';
      for (c = 0; 3 >= c; c++)
        (b = (a >>> (8 * c)) & 255),
          (e = '0' + b.toString(16)),
          (d += e.substr(e.length - 2, 2));
      return d;
    }
    function n(a) {
      a = a.replace(/\r\n/g, '\n');
      for (var b = '', c = 0; c < a.length; c++) {
        var d = a.charCodeAt(c);
        128 > d
          ? (b += String.fromCharCode(d))
          : d > 127 && 2048 > d
          ? ((b += String.fromCharCode((d >> 6) | 192)),
            (b += String.fromCharCode((63 & d) | 128)))
          : ((b += String.fromCharCode((d >> 12) | 224)),
            (b += String.fromCharCode(((d >> 6) & 63) | 128)),
            (b += String.fromCharCode((63 & d) | 128)));
      }
      return b;
    }
    var o,
      p,
      q,
      r,
      s,
      t,
      u,
      v,
      w,
      x = [],
      y = 7,
      z = 12,
      A = 17,
      B = 22,
      C = 5,
      D = 9,
      E = 14,
      F = 20,
      G = 4,
      H = 11,
      I = 16,
      J = 23,
      K = 6,
      L = 10,
      M = 15,
      N = 21;
    for (
      a = n(a),
        x = l(a),
        t = 1732584193,
        u = 4023233417,
        v = 2562383102,
        w = 271733878,
        o = 0;
      o < x.length;
      o += 16
    )
      (p = t),
        (q = u),
        (r = v),
        (s = w),
        (t = h(t, u, v, w, x[o + 0], y, 3614090360)),
        (w = h(w, t, u, v, x[o + 1], z, 3905402710)),
        (v = h(v, w, t, u, x[o + 2], A, 606105819)),
        (u = h(u, v, w, t, x[o + 3], B, 3250441966)),
        (t = h(t, u, v, w, x[o + 4], y, 4118548399)),
        (w = h(w, t, u, v, x[o + 5], z, 1200080426)),
        (v = h(v, w, t, u, x[o + 6], A, 2821735955)),
        (u = h(u, v, w, t, x[o + 7], B, 4249261313)),
        (t = h(t, u, v, w, x[o + 8], y, 1770035416)),
        (w = h(w, t, u, v, x[o + 9], z, 2336552879)),
        (v = h(v, w, t, u, x[o + 10], A, 4294925233)),
        (u = h(u, v, w, t, x[o + 11], B, 2304563134)),
        (t = h(t, u, v, w, x[o + 12], y, 1804603682)),
        (w = h(w, t, u, v, x[o + 13], z, 4254626195)),
        (v = h(v, w, t, u, x[o + 14], A, 2792965006)),
        (u = h(u, v, w, t, x[o + 15], B, 1236535329)),
        (t = i(t, u, v, w, x[o + 1], C, 4129170786)),
        (w = i(w, t, u, v, x[o + 6], D, 3225465664)),
        (v = i(v, w, t, u, x[o + 11], E, 643717713)),
        (u = i(u, v, w, t, x[o + 0], F, 3921069994)),
        (t = i(t, u, v, w, x[o + 5], C, 3593408605)),
        (w = i(w, t, u, v, x[o + 10], D, 38016083)),
        (v = i(v, w, t, u, x[o + 15], E, 3634488961)),
        (u = i(u, v, w, t, x[o + 4], F, 3889429448)),
        (t = i(t, u, v, w, x[o + 9], C, 568446438)),
        (w = i(w, t, u, v, x[o + 14], D, 3275163606)),
        (v = i(v, w, t, u, x[o + 3], E, 4107603335)),
        (u = i(u, v, w, t, x[o + 8], F, 1163531501)),
        (t = i(t, u, v, w, x[o + 13], C, 2850285829)),
        (w = i(w, t, u, v, x[o + 2], D, 4243563512)),
        (v = i(v, w, t, u, x[o + 7], E, 1735328473)),
        (u = i(u, v, w, t, x[o + 12], F, 2368359562)),
        (t = j(t, u, v, w, x[o + 5], G, 4294588738)),
        (w = j(w, t, u, v, x[o + 8], H, 2272392833)),
        (v = j(v, w, t, u, x[o + 11], I, 1839030562)),
        (u = j(u, v, w, t, x[o + 14], J, 4259657740)),
        (t = j(t, u, v, w, x[o + 1], G, 2763975236)),
        (w = j(w, t, u, v, x[o + 4], H, 1272893353)),
        (v = j(v, w, t, u, x[o + 7], I, 4139469664)),
        (u = j(u, v, w, t, x[o + 10], J, 3200236656)),
        (t = j(t, u, v, w, x[o + 13], G, 681279174)),
        (w = j(w, t, u, v, x[o + 0], H, 3936430074)),
        (v = j(v, w, t, u, x[o + 3], I, 3572445317)),
        (u = j(u, v, w, t, x[o + 6], J, 76029189)),
        (t = j(t, u, v, w, x[o + 9], G, 3654602809)),
        (w = j(w, t, u, v, x[o + 12], H, 3873151461)),
        (v = j(v, w, t, u, x[o + 15], I, 530742520)),
        (u = j(u, v, w, t, x[o + 2], J, 3299628645)),
        (t = k(t, u, v, w, x[o + 0], K, 4096336452)),
        (w = k(w, t, u, v, x[o + 7], L, 1126891415)),
        (v = k(v, w, t, u, x[o + 14], M, 2878612391)),
        (u = k(u, v, w, t, x[o + 5], N, 4237533241)),
        (t = k(t, u, v, w, x[o + 12], K, 1700485571)),
        (w = k(w, t, u, v, x[o + 3], L, 2399980690)),
        (v = k(v, w, t, u, x[o + 10], M, 4293915773)),
        (u = k(u, v, w, t, x[o + 1], N, 2240044497)),
        (t = k(t, u, v, w, x[o + 8], K, 1873313359)),
        (w = k(w, t, u, v, x[o + 15], L, 4264355552)),
        (v = k(v, w, t, u, x[o + 6], M, 2734768916)),
        (u = k(u, v, w, t, x[o + 13], N, 1309151649)),
        (t = k(t, u, v, w, x[o + 4], K, 4149444226)),
        (w = k(w, t, u, v, x[o + 11], L, 3174756917)),
        (v = k(v, w, t, u, x[o + 2], M, 718787259)),
        (u = k(u, v, w, t, x[o + 9], N, 3951481745)),
        (t = c(t, p)),
        (u = c(u, q)),
        (v = c(v, r)),
        (w = c(w, s));
    let O = m(t) + m(u) + m(v) + m(w);
    console.log(O,"O的结果");
    
    return O.toLowerCase();
  }
}
